<template>
    <div>
        <div class="ps">
            源码地址: https://github.com/bubkoo/html-to-image
        </div>
        <div>
            <el-button @click="html2Image">div转图片</el-button>
            <el-button @click="html2ImageAndDownload">div转图片并下载</el-button>

        </div>
        <div id="my-node" class="container">
            111
        </div>

    </div>
</template>
  
<script>
/* ES6 */
import * as htmlToImage from 'html-to-image';
export default {
    data() {
        return {
        }
    },
    created() {
    },
    methods: {
        html2Image() {
            var node = document.getElementById('my-node');
            htmlToImage.toPng(node)
                .then(function (dataUrl) {
                    var img = new Image();
                    img.src = dataUrl;
                    document.body.appendChild(img);
                })
                .catch(function (error) {
                    console.error('oops, something went wrong!', error);
                });
        },
        html2ImageAndDownload() {
            const that = this
            htmlToImage.toPng(document.getElementById('my-node'))
                .then(function (dataUrl) {
                    that.download(dataUrl, 'my-node.png');
                });
        },
        //qrBase64是后台传回来的base64数据
        download(qrBase64) {
            // 这里是获取到的图片base64编码,这里只是个例子哈，要自行编码图片替换这里才能测试看到效果
            const imgUrl = `${qrBase64}`
            // 如果浏览器支持msSaveOrOpenBlob方法（也就是使用IE浏览器的时候），那么调用该方法去下载图片
            if (window.navigator.msSaveOrOpenBlob) {
                const bstr = atob(imgUrl.split(',')[1])
                let n = bstr.length
                const u8arr = new Uint8Array(n)
                while (n--) {
                    u8arr[n] = bstr.charCodeAt(n)
                }
                const blob = new Blob([u8arr])
                window.navigator.msSaveOrOpenBlob(blob, 'chart-download' + '.' + 'png')
            } else {
                // 这里就按照chrome等新版浏览器来处理
                const a = document.createElement('a')
                a.href = imgUrl
                a.setAttribute('download', 'chart-download')
                a.click()
            }
        }
    }
}
</script>
<style lang="scss" scoped>
.container {
    background-color: burlywood;
    height: 300px;
}
</style>